package com.bd.wechat.service.impl;

import cn.hutool.json.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.bd.wechat.utils.ConstantWxUtils;
import com.bd.wechat.utils.HttpClientUtils;
import lombok.extern.slf4j.Slf4j;
import okhttp3.HttpUrl;
import okhttp3.Request;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;

@Service
@Slf4j
public class WechatService {
    public static final String WEI_XIN_API_URL = "https://api.weixin.qq.com/cgi-bin/token";

    public String getAccessToken(String code) throws Exception {
        String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                "?appid=%s" +
                "&secret=%s" +
                "&code=%s" +
                "&grant_type=authorization_code";

        //拼接三个参数 ：id  秘钥 和 code值
        String accessTokenUrl = String.format(
                baseAccessTokenUrl,
                ConstantWxUtils.WX_OPEN_APP_ID,
                ConstantWxUtils.WX_OPEN_APP_SECRET,
                code
        );

        String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);

        //从accessTokenInfo字符串获取出来两个值 accsess_token 和 openid
        //把accessTokenInfo字符串转换map集合，根据map里面key获取对应值
        //使用json转换工具 Gson
        HashMap mapAccessToken = JSONObject.parseObject(accessTokenInfo, HashMap.class);
        String access_token = (String) mapAccessToken.get("access_token");
        String openid = (String) mapAccessToken.get("openid");

        log.info("access_token:{},openid:{}", access_token, openid);


        return access_token;
    }
}
